package org.styx.seata.tcc.order.service;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.styx.seata.tcc.order.domain.Order;
import org.styx.seata.tcc.order.mapper.OrderMapper;
import org.styx.seata.tcc.order.tcc.OrderTccAction;

/**
 * @date 2021/8/9
 * @auther uranus
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderService {
    private final  AccountService accountService;
    private final StorageService storageService;
    private final OrderMapper orderMapper;
    private final OrderTccAction orderTccAction;

    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     *  简单说：下订单->扣库存->减余额->改状态
     * 1,测试ＧlobalTransactionl未
     *    可以看到账户和库存都已经减少，订单已经生成，而订单状态却是未完成，这在生产环境中是很严重的问题
     * 2，开启GlobalTransactional测试，测试 一下也不错
     *
    */
    //创建TM ->连接TC->注册全局事务 - >全局事务
    @GlobalTransactional(name = "create-tcc-order",rollbackFor =
            Exception.class)
    public void create(Order order) {
        log.info("------->下单开始");
        //不再执行数据库操作
        //orderMapper.insert(order);
        orderTccAction.prepareCreateOrder(null,order.getId(),order.getUserId(),
                order.getProductId(),order.getCount(),order.getMoney());
        
        //远程调用库存服务扣减库存
        log.info("------->order-service中扣减库存开始-----------------");
        storageService.decrease(order.getProductId(),order.getCount());
        log.info("------->order-service中扣减库存结束-----------------");

        //远程调用账户服务扣减余额
        log.info("------->order-service中扣减余额开始-----------------");
        accountService.decrease(order.getUserId(),order.getMoney());
        log.info("------->order-service中扣减余额结束-----------------");

        //修改订单状态为已完成
        log.info("------->order-service中修改订单状态开始-------------");
        orderMapper.update(order.getUserId(),1);
        log.info("------->order-service中修改订单状态结束-------------");


        log.info("------->下单结束");
    }

}
